package g

import (
	"encoding/json"
	"log"
	"os"
	"sync"

	"github.com/toolkits/file"
)

type AgentConfig struct {
	Enabled  bool   `json:"enabled"`
	Addr     string `json:"addr"`
	Interval int    `json:"interval"`
	Timeout  int    `json:"timeout"`
}

type GlobalConfig struct {
	Debug    bool         `json:"debug"`
	Hostname string       `json:"hostname"`
	Agent    *AgentConfig `json:"agent"`
}

var (
	ConfigFile string
	config     *GlobalConfig
	lock       = new(sync.RWMutex)
)

func Config() *GlobalConfig {
	lock.RLock()
	defer lock.RUnlock()
	return config
}

/*
	Description: 函数功能
	1、取得配置hostname,Hostname未配置则取系统主机名

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func Hostname() (string, error) {
	hostname := Config().Hostname
	if hostname != "" {
		return hostname, nil
	}

	hostname, err := os.Hostname()
	if err != nil {
		log.Println("ERROR: os.Hostname() fail", err)
	}
	return hostname, err
}

/*
	Description: 解析json配置文件

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func ParseConfig(cfg string) {
	if cfg == "" {
		log.Fatalln("use -c to specify configuration file")
	}

	if !file.IsExist(cfg) {
		log.Fatalln("config file:", cfg, "is not existent. maybe you need `mv cfg.example.json cfg.json`")
	}

	ConfigFile = cfg

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		log.Fatalln("read config file:", cfg, "fail:", err)
	}

	var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		log.Fatalln("parse config file:", cfg, "fail:", err)
	}

	lock.Lock()
	defer lock.Unlock()

	config = &c

	log.Println("read config file:", cfg, "successfully")
}

/*
	Description: 函数功能
	1、设置配置

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func SetConfig(c *GlobalConfig) {

	lock.Lock()
	defer lock.Unlock()

	config = c
}
